package com.example.bingobox.ui.schedule;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.os.Environment;
import android.widget.Toast;
import android.app.DatePickerDialog;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.text.TextWatcher;
import android.text.Editable;
import com.example.bingobox.view.ClockTimeSelector;
import com.example.bingobox.adapter.TimeLabelAdapter;
import com.example.bingobox.model.Task.TimeLabel;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import java.util.Calendar;
import java.util.UUID;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.bingobox.R;
import com.example.bingobox.model.Task;
import com.example.bingobox.model.TodoBoxData;
import com.google.gson.Gson;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.io.File;
import java.io.FileWriter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.example.bingobox.adapter.TaskAdapter;

public class TaskListFragment extends Fragment implements TaskAdapter.OnTaskStatusChangeListener, 
    TaskAdapter.TaskActionListener, TimeLabelAdapter.OnTimeLabelActionListener {
    private static final String ARG_SHOW_TYPE = "show_type";
    private int showType; // 使用TaskAdapter中定义的常量
    private List<Task> tasks = new ArrayList<>();
    private TaskAdapter adapter;
    private RecyclerView recyclerView;
    private final Gson gson = new Gson();

    public static TaskListFragment newInstance(int showType) {
        TaskListFragment fragment = new TaskListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SHOW_TYPE, showType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            showType = getArguments().getInt(ARG_SHOW_TYPE, TaskAdapter.SHOW_INCOMPLETE);
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 根据showType选择不同的布局
        int layoutId = (showType == TaskAdapter.SHOW_SEARCH) ? R.layout.fragment_search_task : R.layout.fragment_task_list;
        View view = inflater.inflate(layoutId, container, false);
        
        recyclerView = view.findViewById(R.id.recycler_tasks);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        
        adapter = new TaskAdapter(tasks, showType, this, this);
        recyclerView.setAdapter(adapter);
        
        // 只在未完成任务页面显示添加按钮
        FloatingActionButton fab = view.findViewById(R.id.fab_add_task);
        if (fab != null) {
            fab.setVisibility(showType == TaskAdapter.SHOW_INCOMPLETE ? View.VISIBLE : View.GONE);
            fab.setOnClickListener(v -> showAddTaskDialog());
        }

        // 如果是搜索页面，设置搜索框
        if (showType == TaskAdapter.SHOW_SEARCH) {
            EditText searchInput = view.findViewById(R.id.search_input);
            if (searchInput != null) {
                searchInput.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {}

                    @Override
                    public void afterTextChanged(Editable s) {
                        String query = s.toString().toLowerCase().trim();
                        filterTasks(query);
                    }
                });
            }
        }
        
        loadTasks();
        return view;
    }

    @Override
    public void onTaskStatusChanged(Task task, boolean completed) {
        try {
            File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
            File todoboxFile = new File(dataDir, "todobox.json");

            if (todoboxFile.exists()) {
                String json = new String(Files.readAllBytes(todoboxFile.toPath()));
                TodoBoxData todoBoxData = gson.fromJson(json, TodoBoxData.class);
                if (todoBoxData != null) {
                    List<Task> allTasks = todoBoxData.getTasks();
                    
                    // 先在文件中更新任务状态
                    for (Task t : allTasks) {
                        if (t.getId().equals(task.getId())) {
                            t.setCompleted(completed);
                            break;
                        }
                    }
                    
                    // 保存到文件
                    try (FileWriter writer = new FileWriter(todoboxFile)) {
                        gson.toJson(todoBoxData, writer);
                    }
                    
                    // 然后从当前列表中移除任务
                    tasks.remove(task);
                    adapter.notifyDataSetChanged();
                    
                    // 最后刷新所有 Fragment
                    Fragment parentFragment = getParentFragment();
                    if (parentFragment instanceof ScheduleFragment) {
                        ((ScheduleFragment) parentFragment).refreshAllFragments();
                    }
                    
                    Toast.makeText(getContext(), 
                        completed ? "任务已完成" : "任务已取消完成", 
                        Toast.LENGTH_SHORT).show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), 
                "更新任务状态失败: " + e.getMessage(), 
                Toast.LENGTH_SHORT).show();
        }
    }

    public void loadTasks() {
        try {
            File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
            File todoboxFile = new File(dataDir, "todobox.json");

            if (todoboxFile.exists()) {
                String json = new String(Files.readAllBytes(todoboxFile.toPath()));
                TodoBoxData todoBoxData = gson.fromJson(json, TodoBoxData.class);
                if (todoBoxData != null && todoBoxData.getTasks() != null) {
                    long currentTime = System.currentTimeMillis();
                    tasks.clear(); // 清空当前列表
                    List<Task> allTasks = todoBoxData.getTasks();
                    
                    // 根据 showType 过滤任务
                    switch (showType) {
                        case TaskAdapter.SHOW_INCOMPLETE: // 未完成
                            // 显示未完成且未过期的任务
                            for (Task task : allTasks) {
                                if (!task.isCompleted() && 
                                    (task.getDeadline() == 0 || task.getDeadline() > currentTime)) {
                                    tasks.add(task);
                                }
                            }
                            break;
                            
                        case TaskAdapter.SHOW_COMPLETED: // 已完成
                            // 显示所有已完成的任务
                            for (Task task : allTasks) {
                                if (task.isCompleted()) {
                                    tasks.add(task);
                                }
                            }
                            break;
                            
                        case TaskAdapter.SHOW_EXPIRED: // 已过期
                            // 显示未完成且已过期的任务
                            for (Task task : allTasks) {
                                if (!task.isCompleted() && 
                                    task.getDeadline() != 0 && 
                                    task.getDeadline() < currentTime) {
                                    tasks.add(task);
                                }
                            }
                            break;

                        case TaskAdapter.SHOW_SEARCH: // 搜索
                            // 搜索页面初始时不显示任何任务
                            tasks.clear();
                            break;
                    }
                    
                    adapter.notifyDataSetChanged();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), 
                "加载任务失败: " + e.getMessage(), 
                Toast.LENGTH_SHORT).show();
        }
    }

    private void saveTaskData(Task task) {
        try {
            File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
            File todoboxFile = new File(dataDir, "todobox.json");

            if (todoboxFile.exists()) {
                String json = new String(Files.readAllBytes(todoboxFile.toPath()));
                TodoBoxData todoBoxData = gson.fromJson(json, TodoBoxData.class);
                if (todoBoxData != null) {
                    List<Task> allTasks = todoBoxData.getTasks();
                    
                    // 找到要更新的任务
                    for (int i = 0; i < allTasks.size(); i++) {
                        Task currentTask = allTasks.get(i);
                        // 检查当前任务是否是我们要更新的任务
                        if (currentTask.getId().equals(task.getId())) {  // 这里的 task 是从 onTaskStatusChanged 传入的任务
                            allTasks.set(i, task);
                            todoBoxData.setTasks(allTasks);
                            
                            // 保存回文件
                            try (FileWriter writer = new FileWriter(todoboxFile)) {
                                gson.toJson(todoBoxData, writer);
                            }
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), 
                "保存任务失败: " + e.getMessage(), 
                Toast.LENGTH_SHORT).show();
        }
    }

    private void showAddTaskDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_task, null);
        EditText nameInput = dialogView.findViewById(R.id.edit_task_name);
        EditText descriptionInput = dialogView.findViewById(R.id.edit_task_description);
        Button deadlineButton = dialogView.findViewById(R.id.btn_set_deadline);
        RecyclerView timeLabelsRecyclerView = dialogView.findViewById(R.id.recycler_time_labels);
        Button addTimeSpanButton = dialogView.findViewById(R.id.btn_add_time_span);
        CheckBox foreverCheckbox = dialogView.findViewById(R.id.checkbox_forever);
        CheckBox hometownCheckbox = dialogView.findViewById(R.id.checkbox_hometown);
        CheckBox residenceCheckbox = dialogView.findViewById(R.id.checkbox_residence);

        // 创建时间标签列表和适配器
        List<TimeLabel> timeLabels = new ArrayList<>();
        TimeLabelAdapter timeLabelAdapter = new TimeLabelAdapter(timeLabels, null);

        // 创建监听器
        TimeLabelAdapter.OnTimeLabelActionListener listener = new TimeLabelAdapter.OnTimeLabelActionListener() {
            @Override
            public void onLabelClick(TimeLabel timeLabel, int position) {
                showEditTimeLabelDialog(timeLabel, timeLabels, timeLabelAdapter);
            }

            @Override
            public void onDelete(TimeLabel timeLabel, int position) {
                timeLabels.remove(position);
                timeLabelAdapter.notifyItemRemoved(position);
            }

            @Override
            public void onEdit(TimeLabel timeLabel, int position) {
                showEditTimeLabelDialog(timeLabel, timeLabels, timeLabelAdapter);
            }
        };

        // 设置监听器
        timeLabelAdapter.setActionListener(listener);

        // 设置RecyclerView
        timeLabelsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        timeLabelsRecyclerView.setAdapter(timeLabelAdapter);

        // 设置添加时间段按钮
        addTimeSpanButton.setOnClickListener(v -> 
            showTimeSpanDialog(timeLabels, timeLabelAdapter));

        // 设置截止日期选择
        Calendar calendar = Calendar.getInstance();
        long[] deadline = {0};

        deadlineButton.setOnClickListener(v -> {
            DatePickerDialog datePickerDialog = new DatePickerDialog(
                requireContext(),
                (view, year, month, dayOfMonth) -> {
                    calendar.set(year, month, dayOfMonth);
                    calendar.set(Calendar.HOUR_OF_DAY, 23);
                    calendar.set(Calendar.MINUTE, 59);
                    calendar.set(Calendar.SECOND, 59);
                    deadline[0] = calendar.getTimeInMillis();
                    deadlineButton.setText(formatDate(deadline[0]));
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
            );
            datePickerDialog.show();
        });

        // 设置永久选项
        foreverCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                deadline[0] = 0;
                deadlineButton.setText(formatDate(0));
                deadlineButton.setEnabled(false);
            } else {
                deadlineButton.setEnabled(true);
            }
        });

        new MaterialAlertDialogBuilder(requireContext())
            .setTitle("添加任务")
            .setView(dialogView)
            .setPositiveButton("确定", (dialog, which) -> {
                String name = nameInput.getText().toString().trim();
                if (name.isEmpty()) {
                    Toast.makeText(getContext(), "请输入任务名称", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 创建新任务
                Task newTask = new Task();
                newTask.setId(UUID.randomUUID().toString());
                newTask.setName(name);
                newTask.setDescription(descriptionInput.getText().toString().trim());
                newTask.setDeadline(deadline[0]);
                newTask.setTimeLabels(new ArrayList<>(timeLabels));
                newTask.setCompleted(false);
                newTask.setHometown(hometownCheckbox.isChecked());
                newTask.setResidence(residenceCheckbox.isChecked());

                // 保存任务
                saveTask(newTask);
            })
            .setNegativeButton("取消", null)
            .show();
    }

    private void showEditTaskDialog(Task task) {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_task, null);
        EditText nameInput = dialogView.findViewById(R.id.edit_task_name);
        EditText descriptionInput = dialogView.findViewById(R.id.edit_task_description);
        Button deadlineButton = dialogView.findViewById(R.id.btn_set_deadline);
        RecyclerView timeLabelsRecyclerView = dialogView.findViewById(R.id.recycler_time_labels);
        Button addTimeSpanButton = dialogView.findViewById(R.id.btn_add_time_span);
        CheckBox foreverCheckbox = dialogView.findViewById(R.id.checkbox_forever);
        CheckBox hometownCheckbox = dialogView.findViewById(R.id.checkbox_hometown);
        CheckBox residenceCheckbox = dialogView.findViewById(R.id.checkbox_residence);

        // 填充现有数据
        nameInput.setText(task.getName());
        descriptionInput.setText(task.getDescription());
        deadlineButton.setText(formatDate(task.getDeadline()));
        foreverCheckbox.setChecked(task.getDeadline() == 0);
        hometownCheckbox.setChecked(task.isHometown());
        residenceCheckbox.setChecked(task.isResidence());

        // 创建时间标签列表和适配器
        List<TimeLabel> timeLabels = new ArrayList<>(task.getTimeLabels());
        TimeLabelAdapter timeLabelAdapter = new TimeLabelAdapter(timeLabels, null);

        // 创建监听器
        TimeLabelAdapter.OnTimeLabelActionListener listener = new TimeLabelAdapter.OnTimeLabelActionListener() {
            @Override
            public void onLabelClick(TimeLabel timeLabel, int position) {
                showEditTimeLabelDialog(timeLabel, timeLabels, timeLabelAdapter);
            }

            @Override
            public void onDelete(TimeLabel timeLabel, int position) {
                timeLabels.remove(position);
                timeLabelAdapter.notifyItemRemoved(position);
            }

            @Override
            public void onEdit(TimeLabel timeLabel, int position) {
                showEditTimeLabelDialog(timeLabel, timeLabels, timeLabelAdapter);
            }
        };

        // 设置监听器
        timeLabelAdapter.setActionListener(listener);

        // 设置RecyclerView
        timeLabelsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        timeLabelsRecyclerView.setAdapter(timeLabelAdapter);

        // 设置添加时间段按钮
        addTimeSpanButton.setOnClickListener(v -> 
            showTimeSpanDialog(timeLabels, timeLabelAdapter));

        // 设置截止日期选择
        Calendar calendar = Calendar.getInstance();
        long[] deadline = {task.getDeadline()};

        deadlineButton.setOnClickListener(v -> {
            DatePickerDialog datePickerDialog = new DatePickerDialog(
                requireContext(),
                (view, year, month, dayOfMonth) -> {
                    calendar.set(year, month, dayOfMonth);
                    deadline[0] = calendar.getTimeInMillis();
                    deadlineButton.setText(formatDate(deadline[0]));
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
            );
            datePickerDialog.show();
        });

        // 设置永久选项
        foreverCheckbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                deadline[0] = 0;
                deadlineButton.setText(formatDate(0));
                deadlineButton.setEnabled(false);
            } else {
                deadlineButton.setEnabled(true);
            }
        });

        new MaterialAlertDialogBuilder(requireContext())
            .setTitle("编辑任务")
            .setView(dialogView)
            .setPositiveButton("确定", (dialog, which) -> {
                String name = nameInput.getText().toString().trim();
                if (name.isEmpty()) {
                    Toast.makeText(getContext(), "请输入任务名称", Toast.LENGTH_SHORT).show();
                    return;
                }

                task.setName(name);
                task.setDescription(descriptionInput.getText().toString().trim());
                task.setDeadline(deadline[0]);
                task.setTimeLabels(new ArrayList<>(timeLabels));
                task.setHometown(hometownCheckbox.isChecked());
                task.setResidence(residenceCheckbox.isChecked());

                // 保存修改后的任务
                saveTaskData(task);
                adapter.notifyDataSetChanged();
            })
            .setNegativeButton("取消", null)
            .show();
    }

    private void saveTask(Task newTask) {
        try {
            File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
            File todoboxFile = new File(dataDir, "todobox.json");

            if (todoboxFile.exists()) {
                String json = new String(Files.readAllBytes(todoboxFile.toPath()));
                TodoBoxData todoBoxData = gson.fromJson(json, TodoBoxData.class);
                if (todoBoxData != null) {
                    List<Task> allTasks = todoBoxData.getTasks();
                    // 在文件中将新任务添加到列表开头
                    allTasks.add(0, newTask);
                    todoBoxData.setTasks(allTasks);

                    // 先保存到文件
                    try (FileWriter writer = new FileWriter(todoboxFile)) {
                        gson.toJson(todoBoxData, writer);
                    }

                    // 立即更新当前页面的任务列表
                    if (showType == TaskAdapter.SHOW_INCOMPLETE) {  // 只在未完成任务页面添加
                        tasks.add(0, newTask);
                        adapter.notifyItemInserted(0);
                        recyclerView.scrollToPosition(0);
                    }

                    // 然后刷新所有 Fragment
                    Fragment parentFragment = getParentFragment();
                    if (parentFragment instanceof ScheduleFragment) {
                        ((ScheduleFragment) parentFragment).refreshAllFragments();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), 
                "保存任务失败: " + e.getMessage(), 
                Toast.LENGTH_SHORT).show();
        }
    }

    private String formatDate(long timestamp) {
        if (timestamp == 0) {
            return "永久";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
        return sdf.format(new Date(timestamp));
    }

    // 实现 TaskActionListener 的方法
    @Override
    public void onEditTask(Task task) {
        showEditTaskDialog(task);
    }

    @Override
    public void onDeleteTask(Task task) {
        new MaterialAlertDialogBuilder(requireContext())
            .setTitle("删除任务")
            .setMessage("确定要删除这个任务吗？")
            .setPositiveButton("确定", (dialog, which) -> {
                tasks.remove(task);
                adapter.notifyDataSetChanged();
                deleteTaskFromFile(task);
            })
            .setNegativeButton("取消", null)
            .show();
    }

    private void deleteTaskFromFile(Task task) {
        try {
            File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
            File todoboxFile = new File(dataDir, "todobox.json");

            if (todoboxFile.exists()) {
                String json = new String(Files.readAllBytes(todoboxFile.toPath()));
                TodoBoxData todoBoxData = gson.fromJson(json, TodoBoxData.class);
                if (todoBoxData != null) {
                    List<Task> allTasks = todoBoxData.getTasks();
                    allTasks.removeIf(t -> t.getId().equals(task.getId()));
                    todoBoxData.setTasks(allTasks);

                    try (FileWriter writer = new FileWriter(todoboxFile)) {
                        gson.toJson(todoBoxData, writer);
                        Toast.makeText(getContext(), 
                            "任务已删除", 
                            Toast.LENGTH_SHORT).show();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), 
                "删除任务失败: " + e.getMessage(), 
                Toast.LENGTH_SHORT).show();
        }
    }

    // 实现 OnTimeLabelActionListener 的方法
    @Override
    public void onLabelClick(TimeLabel timeLabel, int position) {
        // 找到包含这个时间标签的任务
        for (Task task : tasks) {
            if (task.getTimeLabels().contains(timeLabel)) {
                List<TimeLabel> timeLabels = task.getTimeLabels();
                TimeLabelAdapter timeLabelAdapter = new TimeLabelAdapter(timeLabels, null);
                TimeLabelAdapter.OnTimeLabelActionListener listener = new TimeLabelAdapter.OnTimeLabelActionListener() {
                    @Override
                    public void onLabelClick(TimeLabel label, int pos) {
                        showEditTimeLabelDialog(label, timeLabels, timeLabelAdapter);
                    }

                    @Override
                    public void onDelete(TimeLabel label, int pos) {
                        timeLabels.remove(pos);
                        timeLabelAdapter.notifyItemRemoved(pos);
                    }

                    @Override
                    public void onEdit(TimeLabel label, int pos) {
                        showEditTimeLabelDialog(label, timeLabels, timeLabelAdapter);
                    }
                };
                timeLabelAdapter.setActionListener(listener);
                showEditTimeLabelDialog(timeLabel, timeLabels, timeLabelAdapter);
                break;
            }
        }
    }

    @Override
    public void onDelete(TimeLabel timeLabel, int position) {
        // 找到包含这个时间标签的任务
        for (Task task : tasks) {
            if (task.getTimeLabels().contains(timeLabel)) {
                List<TimeLabel> timeLabels = task.getTimeLabels();
                timeLabels.remove(timeLabel);
                adapter.notifyDataSetChanged();
                saveTaskData(task);  // 保存更改
                Toast.makeText(getContext(), "时间段已删除", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    }

    @Override
    public void onEdit(TimeLabel timeLabel, int position) {
        // 找到包含这个时间标签的任务
        for (Task task : tasks) {
            if (task.getTimeLabels().contains(timeLabel)) {
                List<TimeLabel> timeLabels = task.getTimeLabels();
                TimeLabelAdapter timeLabelAdapter = new TimeLabelAdapter(timeLabels, null);
                TimeLabelAdapter.OnTimeLabelActionListener listener = new TimeLabelAdapter.OnTimeLabelActionListener() {
                    @Override
                    public void onLabelClick(TimeLabel label, int pos) {
                        showEditTimeLabelDialog(label, timeLabels, timeLabelAdapter);
                    }

                    @Override
                    public void onDelete(TimeLabel label, int pos) {
                        timeLabels.remove(pos);
                        timeLabelAdapter.notifyItemRemoved(pos);
                    }

                    @Override
                    public void onEdit(TimeLabel label, int pos) {
                        showEditTimeLabelDialog(label, timeLabels, timeLabelAdapter);
                    }
                };
                timeLabelAdapter.setActionListener(listener);
                showEditTimeLabelDialog(timeLabel, timeLabels, timeLabelAdapter);
                break;
            }
        }
    }

    // 添加时间段对话框
    private void showTimeSpanDialog(List<Task.TimeLabel> timeLabels, TimeLabelAdapter adapter) {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_timespan, null);
        
        // 获取视图引用
        ClockTimeSelector clockTimeSelector = dialogView.findViewById(R.id.clock_time_selector);
        TextView selectedTimeText = dialogView.findViewById(R.id.text_selected_time);
        ChipGroup dayTypeGroup = dialogView.findViewById(R.id.chip_group_day_types);
        Chip workdayChip = dialogView.findViewById(R.id.chip_workday);
        Chip companionChip = dialogView.findViewById(R.id.chip_companion);
        Chip freedayChip = dialogView.findViewById(R.id.chip_freeday);

        // 设置时钟选择器的监听器
        clockTimeSelector.setOnTimeChangedListener((startHour, startMinute, endHour, endMinute) -> {
            selectedTimeText.setText(String.format(Locale.getDefault(), 
                "%02d:%02d-%02d:%02d", startHour, startMinute, endHour, endMinute));
        });

        // 显示对话框
        new MaterialAlertDialogBuilder(requireContext())
            .setTitle("添加时间段")
            .setView(dialogView)
            .setPositiveButton("确定", (dialog, which) -> {
                // 获取选中的日期类型
                String dayType = null;
                if (workdayChip.isChecked()) {
                    dayType = "工作日";
                } else if (companionChip.isChecked()) {
                    dayType = "陪伴日";
                } else if (freedayChip.isChecked()) {
                    dayType = "自由日";
                }

                if (dayType == null) {
                    Toast.makeText(getContext(), "请选择日期类型", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 创建新的时间标签
                Task.TimeLabel timeLabel = new Task.TimeLabel();
                timeLabel.setDayType(dayType);
                timeLabel.setStartHour(clockTimeSelector.getStartHour());
                timeLabel.setStartMinute(clockTimeSelector.getStartMinute());
                timeLabel.setEndHour(clockTimeSelector.getEndHour());
                timeLabel.setEndMinute(clockTimeSelector.getEndMinute());

                // 添加到列表并更新界面
                timeLabels.add(timeLabel);
                adapter.notifyDataSetChanged();
            })
            .setNegativeButton("取消", null)
            .show();
    }

    private void showEditTimeLabelDialog(TimeLabel timeLabel, List<TimeLabel> timeLabels, TimeLabelAdapter adapter) {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_timespan, null);
        
        // 获取视图引用
        ClockTimeSelector clockTimeSelector = dialogView.findViewById(R.id.clock_time_selector);
        TextView selectedTimeText = dialogView.findViewById(R.id.text_selected_time);
        ChipGroup dayTypeGroup = dialogView.findViewById(R.id.chip_group_day_types);
        Chip workdayChip = dialogView.findViewById(R.id.chip_workday);
        Chip companionChip = dialogView.findViewById(R.id.chip_companion);
        Chip freedayChip = dialogView.findViewById(R.id.chip_freeday);

        // 设置现有值
        clockTimeSelector.setTime(
            timeLabel.getStartHour(),
            timeLabel.getStartMinute(),
            timeLabel.getEndHour(),
            timeLabel.getEndMinute()
        );

        switch (timeLabel.getDayType()) {
            case "工作日":
                workdayChip.setChecked(true);
                break;
            case "陪伴日":
                companionChip.setChecked(true);
                break;
            case "自由日":
                freedayChip.setChecked(true);
                break;
        }

        // 设置时钟选择器的监听器
        clockTimeSelector.setOnTimeChangedListener((startHour, startMinute, endHour, endMinute) -> {
            selectedTimeText.setText(String.format(Locale.getDefault(), 
                "%02d:%02d-%02d:%02d", startHour, startMinute, endHour, endMinute));
        });

        // 显示对话框
        new MaterialAlertDialogBuilder(requireContext())
            .setTitle("编辑时间段")
            .setView(dialogView)
            .setPositiveButton("确定", (dialog, which) -> {
                // 获取选中的日期类型
                String dayType = null;
                if (workdayChip.isChecked()) {
                    dayType = "工作日";
                } else if (companionChip.isChecked()) {
                    dayType = "陪伴日";
                } else if (freedayChip.isChecked()) {
                    dayType = "自由日";
                }

                if (dayType == null) {
                    Toast.makeText(getContext(), "请选择日期类型", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 更新时间值
                timeLabel.setDayType(dayType);
                timeLabel.setStartHour(clockTimeSelector.getStartHour());
                timeLabel.setStartMinute(clockTimeSelector.getStartMinute());
                timeLabel.setEndHour(clockTimeSelector.getEndHour());
                timeLabel.setEndMinute(clockTimeSelector.getEndMinute());

                // 找到包含这个时间标签的任务并保存
                for (Task task : tasks) {
                    if (task.getTimeLabels().contains(timeLabel)) {
                        saveTaskData(task);
                        adapter.notifyDataSetChanged();
                        break;
                    }
                }
            })
            .setNegativeButton("取消", null)
            .show();
    }

    @Override
    public void onFavoriteTask(Task task, boolean favorite) {
        task.setFavorite(favorite);
        saveTaskData(task);  // 保存到文件
        adapter.notifyDataSetChanged();  // 刷新界面
        Toast.makeText(getContext(), 
            favorite ? "已添加到收藏" : "已取消收藏", 
            Toast.LENGTH_SHORT).show();
    }

    private void filterTasks(String query) {
        if (showType != TaskAdapter.SHOW_SEARCH) return;

        try {
            File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
            File todoboxFile = new File(dataDir, "todobox.json");

            if (todoboxFile.exists()) {
                String json = new String(Files.readAllBytes(todoboxFile.toPath()));
                TodoBoxData todoBoxData = gson.fromJson(json, TodoBoxData.class);
                if (todoBoxData != null && todoBoxData.getTasks() != null) {
                    List<Task> allTasks = todoBoxData.getTasks();
                    List<Task> filteredTasks = new ArrayList<>();

                    if (!query.isEmpty()) {
                        for (Task task : allTasks) {
                            String name = task.getName().toLowerCase();
                            String description = task.getDescription() != null ? task.getDescription().toLowerCase() : "";
                            if (name.contains(query) || description.contains(query)) {
                                filteredTasks.add(task);
                            }
                        }
                    }

                    tasks.clear();
                    tasks.addAll(filteredTasks);
                    adapter.notifyDataSetChanged();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), 
                "搜索任务失败: " + e.getMessage(), 
                Toast.LENGTH_SHORT).show();
        }
    }
} 